package com.ihr360.commons.model.type;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ihr360.commons.model.annotation.EnumData;
import com.ihr360.commons.serializer.jackson.EnumDataSerializer;

import java.sql.Date;
import java.sql.Time;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.List;

@EnumData
@JsonSerialize(using = EnumDataSerializer.class)
public enum SalaryFieldValueType {
    NUMBER("数值型", Double.class, null),
    DATE("日期", Date.class, "yyyy-MM-dd"),
    TIME("时间", Time.class, "HH:mm"),
	DATETIME("日期时间", java.util.Date.class, "yyyy-MM-dd HH:mm"),
    TEXT("文本型", String.class, null),
    ARRAY("数组", List.class, null);
    private String title;
    
    private String pattern;

    private final Class<?> type;

    public String getTitle() {
        return title;
    }

    public String getPattern() {
		return pattern;
	}

	SalaryFieldValueType(String title, Class<?> type, String pattern) {
        this.type = type;
        this.title = title;
        this.pattern = pattern;
    }

    @JsonCreator
    public static SalaryFieldValueType factory(@JsonProperty(value = "id") String id) {
        return SalaryFieldValueType.valueOf(id);
    }

    public static SalaryFieldValueType valueOf(Class<?> type) {
        if (Number.class.isAssignableFrom(type)) {
            return NUMBER;
        }
        if (java.util.Date.class.isAssignableFrom(type)) {
            return DATETIME;
        }
        if (Date.class.isAssignableFrom(type)) {
            return DATE;
        }
        if (Time.class.isAssignableFrom(type)) {
            return TIME;
        }
        if (String.class.isAssignableFrom(type)) {
            return TEXT;
        }
        if (List.class.isAssignableFrom(type)) {
            return ARRAY;
        }
        return null;
    }

    public Class<?> getType() {
        return type;
    }

    public Format getFormat(String pattern, RoundingMode roundingMode) {
        if (java.util.Date.class.isAssignableFrom(getType())) {
            return new SimpleDateFormat(this.pattern);
        }
        if (Number.class.isAssignableFrom(getType())) {
            DecimalFormat format = new DecimalFormat(pattern);
            format.setRoundingMode(roundingMode.getJavaRoundingMode());
            return format;
        }
        return null;
    }
}
